<style lang="less">
    @import './user-profiles.less';
</style>

<template>
    <div class="user-profiles-view">
        <Card>
            <p slot="title">
                <Icon type="person"></Icon>
                个人信息
            </p>
            <div>
                <Form ref="userForm" :model="fields" :rules="rules" label-width="80" label-position="left">
                    <Row :gutter="16">
                        <Col span="6">
                        <FormItem label="真实姓名" prop="realname">
                            <Input v-model="fields.realname" disabled="true" placeholder="请输入真实姓名"></Input>
                        </FormItem>
                        </Col>
                        <Col span="6" v-if="isAgent">
                        <FormItem label="身份证号码" prop="identify_card">
                            <Input v-model="fields.identify_card" disabled="true" placeholder="身份证号码"></Input>
                        </FormItem>
                        </Col>
                    </Row>

                    <Row :gutter="16">
                        <Col span="6">
                        <FormItem label="邮箱账号" prop="email">
                            <Input v-model="fields.email" placeholder="电子邮箱"></Input>
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="手机号码" prop="mobile">
                            <Input v-model="fields.mobile" placeholder="手机号码"></Input>
                        </FormItem>
                        </Col>
                    </Row>

                    <Row :gutter="16">
                        <Col span="6">
                        <FormItem label="性别" prop="sex">
                            <Select v-model="fields.sex">
                                <Option value="0">保密</Option>
                                <Option value="1">男</Option>
                                <Option value="2">女</Option>
                            </Select>
                        </FormItem>
                        </Col>
                    </Row>

                    <Row :gutter="16" v-if="isAgent">
                        <Col span="6" >
                            <FormItem label="账户余额">
                                <span class="balance">{{ user.balance }} 元</span>
                            </FormItem>
                        </Col>
                        <Col span="6" >
                            <FormItem label="账户积分">
                                <span class="balance">{{ user.score }} 个</span>
                            </FormItem>
                        </Col>
                    </Row>

                    <Row :gutter="16">
                        <Col span="6">
                        <FormItem label="代理级别" v-if="isAgent">
                            {{ user.extension.agent_level }}级代理商
                        </FormItem>
                        <FormItem label="用户级别" v-else>
                            {{ user.roles_text }}
                        </FormItem>
                        </Col>
                    </Row>

                    <FormItem>
                        <Button type="primary" @click="handleSubmit">保存</Button>
                        <Button type="ghost" style="margin-left: 10px" @click="handleCancel">取消</Button>
                        <Button type="text" style="color: #5191ff;" @click="editPasswordModal = !editPasswordModal">密码修改</Button>
                    </FormItem>
                </Form>
            </div>
        </Card>

        <Modal v-model="editPasswordModal" :width="300" :closable='false' :mask-closable=false>
            <p slot="header">密码修改</p>
            <Form ref="passwordForm" :model="passwords"  label-width="80" label-position="left">
                <FormItem label="原始密码" prop="old_password">
                    <Input type="password" v-model="passwords.old_password"></Input>
                </FormItem>
                <FormItem label="新密码" prop="password">
                    <Input type="password" v-model="passwords.password"></Input>
                </FormItem>
                <FormItem label="确认新密码" prop="re_password">
                    <Input type="password" v-model="passwords.re_password"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelEditPassword">取消</Button>
                <Button type="primary" :loading="savePassLoading" @click="handleEditPassword">确认修改</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import storage from '@/libs/storage';
    import { mapState } from 'vuex';
    import md5 from 'md5';

    export default {
        name: 'user-profiles',
        data() {
            const validePhone = (rule, value, callback) => {
                var re = /^1[0-9]{10}$/;
                if (!re.test(value)) {
                    callback(new Error('请输入正确格式的手机号'));
                } else {
                    callback();
                }
            };
            const valideRePassword = (rule, value, callback) => {
                if (value !== this.passwords.password) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            };

            return {
                editPasswordModal: false,
                savePassLoading: false,

                fields: {
                    name: '',
                    email: '',
                    realname: '',
                    identify_card: '',
                    mobile: '',
                    sex: '0',
                },

                passwords: {
                    old_password: '',
                    password: '',
                    re_password: ''
                },

                rules: {
                    email: [
                        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
                        { type: 'email', message: '电子邮箱格式错误', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请填写手机号码', trigger: 'blur' },
                        { validator: validePhone }
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'blur' }
                    ],
                },

                passwords_rules: {
                    old_password: [
                        { required: true, message: '请输入原始密码', trigger: 'blur' },
                        { type: 'string', min: 6, max: 18, massage: '密码必须6~18个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
                        { type: 'string', min: 6, max: 18, massage: '密码必须6~18个字符', trigger: 'blur' }
                    ],
                    re_password: [
                        { required: true, message: '请再次输入新密码', trigger: 'blur' },
                        { validator: valideRePassword, trigger: 'blur' }
                    ]
                }
            };
        },

        computed: {
            ...mapState({
                user: state => state.user.user
            }),

            isAgent: function () {
                if (this.user && this.user.hasOwnProperty('roles_name') && util.oneOf('agent', this.user.roles_name)) {
                    return true;
                }

                return false;
            }
        },

        methods: {
            handleSubmit() {
                this.$refs.userForm.validate((valid) => {
                    if (valid) {
                        this.update(this.fields);
                    } else {
                        this.$Message.error('验证失败');
                    }
                });
            },

            update (data) {
                util.api().patch(`/admin/api/user/profiles`, data).then((resp) => {
                    if (resp.data.status == true) {
                        this.$Message.success(resp.data.message);
                        storage.set('user', resp.data.data);
                        this.$emit('setUser', resp.data.data);
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                }).catch((e) => {
                    util.handleApiException(e, this, '修改个人信息失败');
                })
            },

            getNewUserInfo (callback) {
                util.api().get('/admin/api/user').then((resp) => {
                    if (resp.data.status == true) {
                        this.$store.dispatch('setUser', resp.data.data);
                    } else {
                        this.$Notice.error({ title: resp.data.message, duration: 1.5 });
                    }
                    callback(resp.data.data);
                })
                .catch((e) => {
                    util.handleApiException(e, this, '获取用户信息失败');
                });
            },

            handleEditPassword () {
                this.savePassLoading = true;
                this.$refs.passwordForm.validate((valid) => {
                    if (valid) {
                        util.api().patch(`/admin/api/user/password/reset`, this.passwords).then((resp) => {
                            if (resp.data.status == true) {
                                this.$Message.success(resp.data.message);
                                storage.set('lockPassword', md5(this.passwords.password));
                                storage.set('user', resp.data.data);
                                this.$emit('setUser', resp.data.data);
                            } else {
                                this.$Message.error(resp.data.message);
                            }
                            this.savePassLoading = false;
                        }).catch((e) => {
                            util.handleApiException(e, this, '密码修改失败');
                            this.savePassLoading = false;
                        })
                    } else {
                        this.$Message.error('表单验证失败');
                        this.savePassLoading = false;
                    }
                });
            },

            cancelEditPassword () {
                this.editPasswordModal = false;
                this.passwords = {
                    old_password: '',
                    password: '',
                    re_password: ''
                };
            }
        },

        mounted() {
            this.getNewUserInfo((user) => {
                this.fields = {
                    email: this.user.email,
                    nickname: this.user.nickname,
                    identify_card: this.user.identify_card,
                    realname: this.user.realname,
                    mobile: this.user.mobile,
                    sex: this.user.sex.toString(),
                }
            })
        }
    };
</script>
